package app

import (
	"fmt"
	"go-demo/common/global"
	"go-demo/mvc/model"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
)

type MySQL struct{}

func (mysql MySQL) Load() {
	client := connectMySQL()
	client.AutoMigrate(&model.User{})
	client.AutoMigrate(&model.QuestionBank{})
	client.AutoMigrate(&model.Question{})
	client.AutoMigrate(&model.QuestionBankAcc{})
	global.App.Mysql = client
}

func connectMySQL() *gorm.DB {
	// mysql 配置
	var (
		user     = global.App.Config.MysqlConfig.User
		password = global.App.Config.MysqlConfig.Password
		host     = global.App.Config.MysqlConfig.Host
		port     = global.App.Config.MysqlConfig.Port
		dbname   = global.App.Config.MysqlConfig.Dbname
	)
	// gorm 配置
	logMode := logger.Default.LogMode(logger.Info)
	nameStrategy := schema.NamingStrategy{
		SingularTable: true,
	}

	// 连接mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbname)
	fmt.Println(dsn)
	client, err := gorm.Open(mysql.New(mysql.Config{
		//mysql 配置
		DSN: dsn,
	}), &gorm.Config{
		//gorm 配置
		NamingStrategy: nameStrategy,
		Logger:         logMode,
	})

	if err != nil {
		log.Panic("mysql 数据库连接错误 ", err)
	}
	log.Println("mysql 数据库连接成功 ", client)

	return client
}
